package logic

import (
	"context"
	"time"

	model "paper-pro/app/assistant/model/assistant"
	"paper-pro/app/assistant/rpc/internal/svc"
	"paper-pro/app/assistant/rpc/pb"
	"paper-pro/pkg/xerr"

	"github.com/jinzhu/copier"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

type UpdateAssistantLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateAssistantLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateAssistantLogic {
	return &UpdateAssistantLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateAssistantLogic) UpdateAssistant(in *pb.UpdateAssistantReq) (*pb.UpdateAssistantResp, error) {
	var assistantInfo model.Assistant
	err := copier.CopyWithOption(&assistantInfo, in.AssistantInfo, copier.Option{DeepCopy: true})
	if err != nil {
		return nil, errors.Wrap(err, "UpdateAssistant数据转换失败")
	}
	if !in.IsCreate {
		objectId, err := primitive.ObjectIDFromHex(in.AssistantInfo.Id)
		if err != nil {
			return nil, errors.Wrapf(err, "UpdateAssistant Assistant id: %s 转换失败", in.AssistantInfo.Id)
		}
		assistantInfo.ID = objectId
	}
	assistantInfo.LastUseAt = time.Now()
	if in.IsCreate {
		err = l.svcCtx.AssistantModel.Insert(l.ctx, &assistantInfo)
		if err != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建新助理失败，err: %v", err)
		}
	} else {
		_, err = l.svcCtx.AssistantModel.Update(l.ctx, &assistantInfo, assistantInfo.UserId)
		if err != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "修改助理失败，err: %v", err)
		}
	}

	return &pb.UpdateAssistantResp{
		AssistantMeta: &pb.AssistantMeta{
			Id:        assistantInfo.ID.Hex(),
			Name:      assistantInfo.AssistantSetting.Name,
			LastUseAt: assistantInfo.LastUseAt.Unix(),
		},
	}, nil
}
